package cz.muni.fi.pa165.sme.web.converters;

import java.util.ArrayList;

import cz.muni.fi.pa165.sme.api.enumeration.SexTO;
import cz.muni.fi.pa165.sme.api.enumeration.UserRoleTO;
import cz.muni.fi.pa165.sme.api.to.SportActivityRecordTO;
import cz.muni.fi.pa165.sme.api.to.UserTO;
import cz.muni.fi.pa165.sme.web.fo.SportActivityRecordFO;
import cz.muni.fi.pa165.sme.web.fo.UserFO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;

/**
 * @author jirankova
 */
public class UserFO2UserTOConverter implements Converter<UserFO, UserTO> {

	@Autowired
	private SportActivityRecordFO2SportActivityRecordTOConverter converter;

	@Override
	public UserTO convert(final UserFO source) {
		if (source == null) {
			return null;
		}

		final UserTO target = new UserTO();

		target.setDateOfBirth(source.getDateOfBirth());
		target.setFirstName(source.getFirstName());
		target.setHeight(source.getHeight());
		target.setId(source.getId());
		target.setSecondName(source.getLastName());
		target.setWeight(source.getWeight());

		if (source.getSex() != null) {
			target.setSexTO(SexTO.valueOf(source.getSex().name()));
		}

		if (source.getSportActivityRecords() == null) {
			target.setSportActivityRecords(null);
		} else {
			target.setSportActivityRecords(new ArrayList<SportActivityRecordTO>());
			for (SportActivityRecordFO sourceRecord : source.getSportActivityRecords()) {
				target.getSportActivityRecords().add(converter.convert(sourceRecord));
			}
		}

		if(source.getRoles() != null){
			if(source.hasRole(UserRoleTO.ADMIN.name())) {
				target.setRoleTO(UserRoleTO.ADMIN);
			} else if(source.hasRole(UserRoleTO.USER.name())) {
				target.setRoleTO(UserRoleTO.USER);
			}
		}
		target.setLogin(source.getLogin());
		target.setPassword(source.getPassword());

		return target;
	}
}
